const BaseHandler = require('../base-handler');
const HTTP_VERBS = require('../../../constants').HTTP_VERBS;
const CriticalErrors = require('../../../constants').CriticalErrors;
const ApplicationEvents = require('../../../constants').ApplicationEvents;
const utils = require('../../../utils');
const {WebRequestError} = require('../../../errors');

class BlueMPRedirectHandler extends BaseHandler {

    get pattern() {
        return "/bluemp/authorize";
    }

    doGET(request, response) {
        var me = this;
        request.query.ref = 'bluemp';
        this.ensureRef(request);
        if (request.query.code) {
            let params = {
                code: request.query.code,
                redirect_uri: this.Controller.getRedirectURI(request)
            };
            this.Controller.getAccessToken('code', params, (result) => {
                if (result.access_token) {
                    me.Controller.getEnterpriseInfo(result.access_token, (result) => {
                        //TODO: Use system configuration instead
                        let selfServiceUserId = 2001;
                        let internalOrderId = 1000;
                        let initialPlanId = 1000;
                        if (result.error) {
                            return response.redirect("/signup?ref=bluemp");
                        }
                        let email = result.email || `bluemp-${result.id}@parllay.cn`;
                        let name = result.username;
                        let password = utils.generateIdentifier(8, 'full');
                        let thirdPartyId = result.id;
                        let locale = request.locale;
                        me.Controller.saveOrUpdateSystemUser(selfServiceUserId, internalOrderId, initialPlanId, name, email, password, request.session.user.refs, locale, thirdPartyId, (result) => {
                            if(!result.success && !result.data) {
                                pageData.success = false;
                                pageData.error = result.error;
                                response.render('console/login', pageData);
                            } else {
                                request.session.user.authenticated = true;
                                request.session.user.id = result.data.id;
                                request.session.user.name = result.data.name;
                                request.session.user.profile_image = me.Controller.getCDNImageURL(result.data.profile_image);
                                request.session.user.ref = result.data.ref;
                                request.session.user.qr_code = result.data.qr_code;
                                response.redirect('/console?from=bluemp');
                            }
                        });
                    });
                } else {
                    me.reportError(ApplicationEvents.WEB_REQUEST_ERROR, 
                                new WebRequestError(result.error, 
                                                    CriticalErrors.WEB_REQUEST_ERROR, 
                                                    request.requestData));
                    response.redirect('/bluemp/redirect');
                }
            });
        } else {
            response.redirect('/signup?ref=bluemp');
        }
    }

    setup() {
        this.registerVerb(HTTP_VERBS.GET, this.doGET);
    }
}

module.exports = BlueMPRedirectHandler;